import 'dart:async';

import 'package:alipay_kit/alipay_kit.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_mine/whl_mine_logic.dart';
import 'package:cave_flutter/utils/whl_toast_utils.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../config/whl_global_config.dart';
import '../../../routes/whl_app_pages.dart';
import 'model/whl_wallet_model.dart';

class WhlWalletLogic extends GetxController {
  ///数据
  WhlWalletModel? walletModel;

  ///页面部分属性
  //顶部余额试图左右间距
  double topItemMarginLr = 39.w;

  //顶部余额试图圆角
  double topItemRadius = 25.w;

  //顶部余额试图最小高度
  double topItemMinHeight = 100.h;

  ///操作数据
  //选择的充值金额
  WhlWalletRechargeItemModel? selRechargeModel;

  //选择的支付方式
  WhlWalletPayTypeModel? selPayModel;

  //自定义金额
  TextEditingController customController = TextEditingController();

  //支付宝回调监听
  // late final StreamSubscription<AlipayResp> _paySubs;

  @override
  void onInit() {
    super.onInit();
    customController.addListener(() {
      _onCustomRecharge(customController.text);
    });
    initData();
    getRechargeList(false);
    getWithdrawAmount();
  }

  //  获取充值产品
  getRechargeList(bool isRefresh) async {
    ResponseData response = await WhlApi.rechargeList.get({});
    if (response.isSuccess()) {
      if (response.data is List) {
        walletModel?.rechargeList = (response.data as List)
            .map((e) => WhlWalletRechargeItemModel.fromJson(e))
            .toList();
      }
      if (!isRefresh && walletModel?.rechargeList?.isNotEmpty == true) {
        //默认第一个
        onSelRechargeItem(walletModel!.rechargeList!.first);
      } else {
        update();
      }
    }
  }

  //  获取可提现金额
  getWithdrawAmount() async {
    ResponseData response = await WhlApi.withdrawAmount.get({});
    if (response.isSuccess() && response.data != null) {
      WhlWalletModel data = WhlWalletModel.fromJson(response.data);
      walletModel?.balance = data.balance;
      walletModel?.unCanWithDrawCoin = data.unCanWithDrawCoin;
      walletModel?.withdrawal = data.withdrawal;
      walletModel?.withdrawalAmount = data.withdrawalAmount;
      walletModel?.walletId = data.walletId;
      update();
    }
  }

  initData() {
    //loading
    walletModel = WhlWalletModel();
    walletModel?.balance = 0;
    walletModel?.unCanWithDrawCoin = 50;
    walletModel?.withdrawalAmount = 0;
    walletModel?.withdrawal = 0;
    walletModel?.rechargeList = [];
    walletModel?.payTypeList = [
      WhlWalletPayTypeModel(key: "1", image: "vip_alipay.png", title: "支付宝"),
      WhlWalletPayTypeModel(key: "2", image: "vip_wechat.png", title: "微信"),
    ];
    //默认第一个
    selPayModel = walletModel?.payTypeList?.first;
    update();
    getWithdrawAmount();
  }

  ///选择金额
  onSelRechargeItem(WhlWalletRechargeItemModel model) {
    selRechargeModel = model;
    customController.text = '';
    update();
  }

  ///自定义金额
  _onCustomRecharge(String price) {
    if (price.isNotEmpty) {
      selRechargeModel = WhlWalletRechargeItemModel(
          nowPrice: int.parse(price), originalPrice: 0);
    }
    update();
  }

  ///选择支付方式
  onSelPayTypeItem(WhlWalletPayTypeModel model) {
    selPayModel = model;
    update();
  }

  ///查看协议
  onCheckProtocol() {}

  ///进入提现
  onPushToWithDraw() {
    Get.toNamed(Routes.withDrawIndexPage);
  }

  ///立即充值
  onRechargeNow() {
    return WhlApi.saveRecharge.post({
      'rechargeAmount': selRechargeModel?.nowPrice,
      'source': 1,
      'caveRechargeId': selRechargeModel?.id,
      "outTradeNo": null,
      "tradeNo": null,
    }).then((value) {
      MyToast.show('充值成功');
      selRechargeModel?.nowFirstCharge = 0;
      getWithdrawAmount();
    });
    // _aliPay();
  }

  ///支付宝支付
  _aliPay() {
    final Map<String, dynamic> bizContent = <String, dynamic>{
      'timeout_express': '30m',
      'product_code': 'QUICK_MSECURITY_PAY',
      'total_amount': '0.01',
      'subject': '1',
      'body': '我是测试数据',
      'out_trade_no': '123456789',
    };
    final Map<String, dynamic> orderInfo = <String, dynamic>{
      'app_id': WHLGlobalConfig.ALIPAY_APPID,
      'biz_content': '',
      'charset': 'utf-8',
      'method': 'alipay.trade.app.pay',
      'timestamp': '2016-07-29 16:55:53',
      'version': '1.0',
    };
    AlipayKitPlatform.instance.pay(orderInfo: orderInfo.toString());
  }

  void _listenPay(AlipayResp resp) {
    final String content = 'pay: ${resp.resultStatus} - ${resp.result}';
    print('支付$content');
  }
}
